package me.firstapp.bts.service.impl;

import java.util.Date;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import me.firstapp.bts.service.OrderJobService;
import me.firstapp.common.exception.StatusHouse;
import me.firstapp.common.json.ListObject;
import me.firstapp.common.module.shop.JsonOrder;
import me.firstapp.common.module.system.JsonApiClient;
import me.firstapp.common.utils.DateUtils;
import me.firstapp.spi.shop.OrderService;
import me.firstapp.spi.system.ApiClientService;

@Service
public class OrderJobServiceImpl implements OrderJobService {

	private static Logger logger = LoggerFactory.getLogger(OrderJobService.class);

	@Autowired
	private OrderService orderService;

	@Autowired
	private ApiClientService apiClientService;

	@Override
	public void cancelOutTimeOrders() {
		long start = System.currentTimeMillis();
		logger.info("..................开始批处理取消订单..................");
		ListObject<JsonApiClient> clientsJson = apiClientService.findAll();
		if (clientsJson != null) {
			List<JsonApiClient> clients = clientsJson.getItems();
			if (clients != null && !clients.isEmpty()) {
				for (JsonApiClient client : clients) {
					ListObject<JsonOrder> orderResult = orderService.findOrders(null, 0, client.getId());
					if (StatusHouse.COMMON_STATUS_OK.getCode().equals(orderResult.getCode())) {
						List<JsonOrder> orders = orderResult.getItems();
						if (orders != null) {
							logger.info("apiKey=" + client.getApiKey() + "总共有" + orders.size() + "个未支付的订单。");
							for (JsonOrder order : orders) {
								Date createTime = order.getCreateTime();
								long hour = DateUtils.getDistanceTimesForHour(createTime, new Date());
								if (hour >= 2) {
									logger.info("订单：" + order.getOrderNo() + "已过" + hour + "小时，即将取消该订单。");
									orderService.cancelOrder(order.getOrderNo(), client.getId());
									logger.info("订单：" + order.getOrderNo() + "已被自动取消");
								}
							}
						}
					}
				}
			}
		}
		logger.info("..................结束批处理取消订单....................耗时===》" + (System.currentTimeMillis() - start));
	}

}
